<template>
    <el-dialog :title="tableTitle" v-model="props.dialogVisible" width="25%" top="15vh" center @open="tableOpen"
        :before-close="cancelClick">
        <div class="bodyBox">
            <el-form ref="ruleFormRef" :model="ruleFormData" :rules="rules" :label-width="dialogLabelWidth"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-row :gutter="20">
                    <!-- 输入框-input，下拉选择-select，单选-radio，开关-switch，日期时间-datetime，日期-date，头像上传-uploadAvatar，文本域-textarea -->
                    <el-col v-for="(i, n) in formData" :key="n" :span="i.span">
                        <el-form-item :label="i.label" :prop="i.prop">
                            <el-input v-if="i.type === 'input'" v-model="ruleFormData[i.prop]"
                                :placeholder="i.placeholder" clearable />
                            <el-input v-if="i.type === 'password'" v-model="ruleFormData[i.prop]"
                                :placeholder="i.placeholder" clearable show-password />
                            <el-select-v2 v-if="i.type === 'select'" v-model="ruleFormData[i.prop]"
                                :placeholder="i.placeholder" clearable :options="i.options" :disabled="i.disabled" />
                            <el-radio-group v-if="i.type === 'radio'" v-model="ruleFormData[i.prop]" class="ml-4">
                                <el-radio v-for="(item, num) in i.radioItems" :key="num" :value="item.value">{{
                                    item.label }}</el-radio>
                            </el-radio-group>
                            <el-switch v-if="i.type === 'switch'" active-text="" inactive-text="" active-color="#2fa1f1"
                                inactive-color="#9c9c9c" v-model="ruleFormData[i.prop]"
                                @change="handleStatusChange(ruleFormData)" />
                            <el-date-picker style="width: 100%;" v-if="i.type === 'dateTime'"
                                v-model="ruleFormData[i.prop]" type="datetime" :placeholder="i.placeholder"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                            <el-date-picker style="width: 100%;" v-if="i.type === 'date'" v-model="ruleFormData[i.prop]"
                                type="date" :placeholder="i.placeholder" value-format="YYYY-MM-DD" />
                            <el-upload v-if="i.type === 'uploadAvatar'" class="avatar-uploader"
                                :http-request="(options: any) => handleCustomUpload(i, options)" :show-file-list="false"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="ruleFormData[i.prop]" :src="ruleFormData[i.prop]" class="avatar" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>
                            <el-input v-if="i.type === 'textarea'" v-model="ruleFormData[i.prop]"
                                :autosize="i.autosize ? i.autosize : { minRows: i.minRows ? i.minRows : 2, maxRows: i.maxRows ? i.maxRows : 4 }"
                                :maxlength="i.maxlength" :placeholder="i.placeholder" show-word-limit type="textarea" />

                            <!-- 详情类 -->
                            <!-- 文字 detailsText -->
                            <span class="detailsTextBox" v-if="i.type === 'detailsText'">{{ ruleFormData[i.prop]
                            }}</span>
                            <!-- 照片墙 photoWall -->
                            <div class="photoWallBox" v-if="i.type === 'photoWall'">
                                <div class="photoWallItem" v-for="(j, n) in ruleFormData[i.prop]" :key="n">
                                    <img class="img" :src="j" />
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancelClick" :loading="btnLoading">关 闭</el-button>
            <el-button type="primary" @click="submitForm()" :loading="btnLoading">{{ submitBtn }}</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang='ts' name="DialogCom">
import { ref, reactive, defineProps } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false,
    },
    btnLoading: {
        type: Boolean,
        default: false,
    },
    tableTitle: {
        type: String,
        default: '',
    },
    // 表单控件数据
    formData: {
        type: Array,
        validator: () => {
            return [];
        }
    },
    // 表单数据
    ruleForm: {
        type: Object,
        default: () => ({}),
    },
    // 表单校验配置
    rules: {
        type: Object,
        default: () => ({}),
    },
    // 确定按钮 的请求方法requestMethod
    requestMethod: {
        type: Function,
        default: () => { },
    },
    submitBtn: {
        type: String,
        default: '确 定',
    },
    dialogLabelWidth: {// label文字宽度
        type: String,
        default: '100px',
    },
})
interface RuleFormData {
    [key: string]: string | number | boolean; // 根据实际值类型调整
}
const ruleFormData: RuleFormData = reactive({})
// 上传图片 开始
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
        ElMessage.error('头像格式只能为jpeg、jpg、png!!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 6) {
        ElMessage.error('头像大小不能超过6MB!')
        return false
    }
    return true
}
const handleCustomUpload = async (i: object, options: any) => {
    try {
        // 1. 创建 FormData 对象
        const formData = new FormData()
        formData.append('file', options.file)

        // 存放请求后得到的地址
        ruleFormData[i.prop] = 'https://img2.baidu.com/it/u=2287614273,1325409419&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800'
    } catch (error: any) {
        // 5. 处理失败情况
        options.onError(error)
        ElMessage.error('上传失败: ' + (error.response?.data?.message || error.message))
    }
}
// 上传图片 结束
const formSize = ref('default')
const emits = defineEmits(['beforeClose', 'dialogSwitch', 'submitForm']);

const ruleFormRef = ref<FormInstance>()
// 确定按钮
const submitForm = () => {
    ruleFormRef.value?.validate().then((valid) => {
        if (valid) {
            emits('submitForm', ruleFormData, props.tableTitle);
        } else {
            return false
        }
    })
}
// 开关事件
const handleStatusChange = ((row: object) => {
    emits('dialogSwitch', row)
})
// 弹窗打开事件
const tableOpen = () => {
    Object.assign(ruleFormData, props.ruleForm);
}
// 弹窗关闭事件
const cancelClick = () => {
    // 清空表单
    ruleFormRef.value?.resetFields();
    emits('beforeClose', false);
}
// 显式暴露方法给父组件
defineExpose({
    cancelClick
});
</script>
<style lang='scss' scoped>
.bodyBox {
    padding: 20px;

    .detailsTextBox {
        color: #000;
        line-height: 20px;
        border-bottom: 1px solid #BBBBBB;
    }

    .photoWallBox {
        .photoWallItem {
            width: 80px;
            height: 80px;
            display: inline-block;
            margin-right: 10px;

            .img {
                width: 100%;
                height: 100%;
            }
        }
    }
}


// 图片上传样式
.avatar-uploader .avatar {
    width: 50px;
    height: 50px;
    display: block;
}
</style>
<style>
/*  头像上传样式  */
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-dialog__header {
    border-bottom: 1px solid #ccc;
}

.dialog-footer {
    padding-top: 20px;
    border-top: 1px solid #ccc;
    text-align: right;

    .el-button {
        background-color: #A4ADB3;
        border: 1px solid #A4ADB3;
        color: #fff;
    }

    .el-button--primary {
        background-color: #DE868F;
        border: 1px solid #DE868F;
    }
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    text-align: center;
}
</style>